package tech.hdis.framework.exception.handlers;


import org.springframework.validation.BindException;
import tech.hdis.framework.exception.chain.AbstractExceptionHandlerChain;
import tech.hdis.framework.exception.exceptions.FieldError;
import tech.hdis.framework.exception.properties.ExceptionProperties;
import tech.hdis.framework.exception.response.ExceptionResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * hibernate验证统一异常返回器
 *
 * @author 黄志文
 */
public class BindExceptionHandler extends AbstractExceptionHandlerChain {

    private static BindExceptionHandler instance = new BindExceptionHandler();

    private BindExceptionHandler() {
    }

    public static BindExceptionHandler getInstance() {
        return instance;
    }

    @Override
    public ExceptionResponse doHandler(Exception exception) {
        if (exception instanceof BindException) {
            BindException validException = (BindException) exception;
            List<FieldError> errors = new ArrayList<>();
            for (org.springframework.validation.FieldError error : validException.getBindingResult().getFieldErrors()) {
                FieldError myFieldError = new FieldError();
                myFieldError.setField(error.getField());
                myFieldError.setMessage(error.getDefaultMessage());
                errors.add(myFieldError);
            }
            return ExceptionResponse.getInstance().code(ExceptionProperties.VALIDATOR_KEY, ExceptionProperties.VALIDATOR_VALUE).fieldErrors(errors);
        }
        return this.getNextHandler().doHandler(exception);
    }
}
